<template>
    <!-- 日历插件 -->
    <div class="container-calender">
        <div class="container-calender-son">
            <FullCalendar
                    id="calendar"
                    class="demo-app-calendar"
                    ref="fullCalendar"
                    :views="eventLimitNum"
                    :eventLimit="true"
                    :eventLimitText="this.eventLimitText"
                    :options="calendarOptions"
            />

            <!-- @eventPositioned="eventPositioned"  -->
            <!-- @eventMouseEnter="eventMouseEnter"  -->
            <!-- @select="select" 选择日期格子添加事件 -->
            <!-- :editable="true"  是否可编辑 -->
            <!-- :longPressDelay="0" 拖动多选时延迟的时间，如果不设置默认是1秒-->
        </div>
        <div></div>
    </div>
</template>
<script>

    import FullCalendar from "@fullcalendar/vue";
    import dayGridPlugin from "@fullcalendar/daygrid";
    import timeGridPlugin from "@fullcalendar/timegrid";
    import interactionPlugin, {Draggable} from "@fullcalendar/interaction";
    // import momentPlugin from '@fullcalendar/moment'
    import dateUtil from "@/utils/dateUtils";
    import moment from "moment";

    export default {
        components: {
            FullCalendar //注册组件
        },
        props: {
            // 日历周末是否显示灰色背景
            businessHours: {
                type: Boolean,
                default: false
            },
            // 选择日历，可多选
            selectDate: {
                type: Function,
                default: null
            },
            // 点击日历，单击日历
            clickDate: {
                type: Function,
                default: null
            },
            // 主页面的数据
            calendarEvents: {
                type: Array,
                default: () => []
            },
            // 点击日历中的事件
            eventClicked: {
                type: Function,
                default: null
            },
            // 日历是否限制在整年
            isWholeYear: {
                type: Boolean,
                default: true
            },
        },
        data() {
            let _this = this;
            return {
                calendarApi: null,
                eventLimitNum: {
                    // 事件显示数量限制(周视图)
                    dayGrid: {
                        eventLimit: 6
                    },
                    // 事件显示数量限制(日视图)
                    timeGrid: {
                        eventLimit: 2 // adjust to 6 only for timeGridWeek/timeGridDay
                    }
                },

                calendarWeekends: false, //是否更改周日显示的位置

                calendarOptions: {
                    dayCellContent: this.dayCon, //自定义日期显示样式
                    dayCellDidMount: this.datev, //自定义日历
                    //插件引入后在此声明后，才可使用
                    plugins: [
                        dayGridPlugin,
                        timeGridPlugin,
                        interactionPlugin //dateClick点击事件和Draggable移动事件需要此插件
                    ],
                    // 限制用户选择的时间范围
                    validRange: {
                        start: '',
                        end: ''
                    },
                    //头部菜单展示
                    headerToolbar: {
                        left: "prev,next today",
                        center: "title",
                        right: ""
                    },
                    customButtons: {
                        prev: {
                            text: '上一月',
                            click: function () {
                                _this.calendarApi.prev();
                                _this.getYearMonth();
                                _this.$emit('getRightCalendarDeta', '');
                                _this.$emit('getCalendarDatas', '');
                            }
                        },
                        next: {
                            text: '下一月',
                            click: function () {
                                _this.calendarApi.next();
                                _this.getYearMonth();
                                _this.$emit('getRightCalendarDeta', '');
                                _this.$emit('getCalendarDatas', '');
                            }
                        },
                        today: {
                            text: '回到今天',
                            click: function () {
                                _this.calendarApi.today()
                                _this.getYearMonth();
                                _this.$emit('getRightCalendarDeta', '');
                                _this.$emit('getCalendarDatas', '');
                                _this.$emit('goBackToday', '');
                            }
                        }
                    },
                    // 顶部按钮的文字显示
                    buttonText: {
                        prev: "上一月",
                        next: "下一月",
                        today: "回到今天",
                    },
                    locale: "zh-cn",
                    selectable: true,
                    selectMirror: true,
                    dateClick: this.dayClick,
                    eventClick: this.eventClick,
                    select: this.select,
                    businessHours: this.businessHours,
                    events: this.calendarEvents,   //测试this.calendarEvents  或者  默认[]
                    eventTimeFormat: {  //显示的时间格式化
                        hour: 'numeric',
                        minute: '2-digit',
                        meridiem: false
                    },
                    displayEventTime: false,
                    displayEventEnd: false,
                    fixedWeekCount: false,
                    unselectAuto: false,
                    eventDidMount: this.eventContent,
                    height: "100%",
                    // eventLimitText: this.eventLimitText,
                    longPressDelay: 0,
                    initialView: "dayGridMonth" //默认展示的日历视图
                }
            };
        },

        mounted() {
            this.calendarApi = this.$refs.fullCalendar.getApi();
            let fullYear = new Date().getFullYear();
            // console.log(fullYear);

            if (this.isWholeYear){
                this.calendarOptions.validRange.start = fullYear + '-' + '01';
            } else {
                this.calendarOptions.validRange.start = "";
            }
            this.calendarOptions.validRange.end = fullYear + '-' + '13';
            // console.log(this.calendarOptions.validRange);
            // console.log(this.calendarApi);
            // console.log(this.$refs.fullCalendar);
            // let newDate = dateUtil.formatDate(new Date());
            // this.getYearMonth();

        },
        watch: {     //监听calendarEvents的变化，进行相应的操作即可
            calendarEvents: function (a, b) {
                //a是value的新值，b是旧值
                // console.log(a);
                // console.log(b);
                this.initData(a);  //把新值传进初始化的函数
            },

        },
        methods: {
            initData(param) {
                this.calendarOptions.events = param
            },
            //上一月
            prev() {
                this.calendarApi.prev();
            },
            //下一月
            next() {
                this.calendarApi.next();
            },
            // 获取现在的年,月
            getYearMonth() {
                let nowYearDate = this.calendarApi.view.currentStart.getFullYear();
                let nowMonthDate = this.calendarApi.view.currentStart.getMonth() + 1;
                // console.log(nowYearDate,nowMonthDate);
                return [nowYearDate, nowMonthDate]
            },
            // 日历回调函数
            dayRender(date) {
                // console.log(date);

            },
            getOrderId(keyword) {
                var newList = null;
                this.calendarEvents.forEach(item => {
                    if (item.title.indexOf(keyword) != -1) {
                        if (item.title.indexOf("请假") != -1) {
                            // alert(item.leaveOrderId);
                            newList = item.leaveOrderId
                        }
                        if (item.title.indexOf("加班") != -1) {
                            // alert(item.overTimeOrderId);
                            newList = item.overTimeOrderId
                        }
                        if (item.title.indexOf("补出勤") != -1) {
                            // alert(item.overTimeOrderId);
                            newList = item.repairOrderId
                        }
                    }
                })
                return newList
            },

            // 判断是否是周末或休或节，改变日期的颜色
            dayCon(arg) {
                // console.log(arg);
                let newDate = dateUtil.formatDate(arg.date);   //获取日期并格式化为年月日格式"2020-07-07"
                // console.log(newDate);
                let dayType = this.getDayType(newDate);  //根据日期拿到数据中当天的工作类型（1休息日, 0工作日, 2节假日）
                // console.log(dayType);
                let weekDay2 = new Date(arg.date).getDay();  //获取周几

                if (weekDay2 == 0 || weekDay2 == 6 || dayType == 1 || dayType == 2) {
                    return {
                        html:
                        '<a style="color: red" class="fc-daygrid-day-number">' +
                        arg.dayNumberText +
                        "</a>"
                    };
                } else {
                    return {
                        html:
                        '<a class="fc-daygrid-day-number">' +
                        arg.dayNumberText +
                        "</a>"
                    };
                }
            },
            // 获取当天的类型
            getDayType(date) {
                let type;
                this.calendarOptions.events.filter(item => {
                    // console.log(item);
                    let date2 = moment(item.start).format("YYYY-MM-DD");
                    // console.log(date2);
                    if (date == date2) {
                        type = item.dayType
                    }
                });
                return type
            },
            // 判断是否是周末，给日历元素添加自定义文字
            datev(arg) {
                // console.log(arg.el.innerHTML);
                // console.log(arg.date.getDay());  //获取周几
                let newDate = dateUtil.formatDate(arg.date);   //获取日期并格式化为年月日格式"2020-07-07"
                // console.log(newDate);
                let dayType = this.getDayType(newDate); //根据日期拿到数据中当天的工作类型（1休息日, 0工作日, 2节假日）
                // console.log(this.calendarEvents);   //主页面传过来的数据，可以获取每一天的数据里的类型
                // if (dayType == 1) {
                //   // 如果是休息日的样式
                //   arg.el.innerHTML =
                //     "<div class=\"fc-daygrid-day-frame fc-scrollgrid-sync-inner\" style='min-height: auto;position: initial;'>" +
                //     "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;'> <span style='font-size: 14px'>休</span> </div>" +
                //     "</div>";
                // } else if (dayType == 1) {
                //   // 类型是工作日的样式（把“休”字去掉）
                //   arg.el.innerHTML =
                //     "<div class=\"fc-daygrid-day-frame fc-scrollgrid-sync-inner\" style='min-height: auto;position: initial;'>" +
                //     "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;'> <span></span> </div>" +
                //     "</div>";

                // } else if (dayType == 2) {
                //   // 类型是节假日的样式（把“休”字改为“节”）
                //   arg.el.innerHTML =
                //     "<div class=\"fc-daygrid-day-frame fc-scrollgrid-sync-inner\" style='min-height: auto;position: initial;'>" +
                //     "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;'> <span style='font-size: 14px'>节</span> </div>" +
                //     "</div>";

                // }

            },
            // 修改事件的样式为红色“休”或红色“节”
            eventContent(arg) {
                // console.log(arg);
                // console.log(arg.event.startStr);
                // console.log(arg.el.innerHTML);
                let dated = dateUtil.formatDate(new Date(arg.event.start));
                // console.log(dated);
                let weekDay = new Date(dated).getDay();
                // console.log(weekDay);

                let dayType = this.getDayType(dated);
                // console.log(dayType);  //（1休息日, 0工作日, 2节假日）

                if (dayType == 1 && (weekDay == 0 || weekDay == 6)) {
                    // 如果是休息日并且是周末的样式
                    arg.el.innerHTML =

                        "<div class=\"fc-daygrid-event-dot\" style='border: 0;margin: 0;'>" +
                        "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;background-color: #f3f3f3;'> <div class='fc-event-title' style='font-style: initial;font-size: 14px;'>休</div> </div>" +
                        "</div>";

                } else if (dayType == 1 && (weekDay == 1 || weekDay == 2 || weekDay == 3 || weekDay == 4 || weekDay == 5)) {
                    // 如果是休息日并且非周末的样式
                    arg.el.innerHTML =

                        "<div class=\"fc-daygrid-event-dot\" style='border: 0;margin: 0;'>" +
                        "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;background-color: #fff;'> <div class='fc-event-title' style='font-style: initial;font-size: 14px;'>休</div> </div>" +
                        "</div>";

                } else if (dayType == 2) {
                    // 如果是节假日的样式
                    arg.el.innerHTML =

                        "<div class=\"fc-daygrid-event-dot\" style='border: 0;margin: 0;'>" +
                        "<div style='position: absolute;top: 0;bottom: 0;width: 100%;display: flex;justify-content: center;align-items: center;color: red;background-color: #ffefad;'> <div class='fc-event-title' style='font-style: initial;font-size: 14px;'>节</div> </div>" +
                        "</div>";

                } else {
                    arg.el.innerHTML
                }
            },
            // 这个方法可以调整周末在第一列还是最后一列
            toggleWeekends() {
                this.calendarWeekends = !this.calendarWeekends;
            },

            // 拖动结束后会触发此事件，更新日历，有数据的格子都会触发一次，回调就是这个格子的所有信息
            eventPositioned(info) {
                // console.log(info),  //返回每个日历格子的对象属性
                //  console.log('事件被放置在日历的最终位置后触发')
            },

            //  当超过规定的时间数量时显示的提示字样，需要配合使用 eventLimitNum 配置最多显示数量
            eventLimitText() {
                return "更多";
            },
            // 切换视图重新加载数据时会触发这个回调
            datesRender(info) {
                console.log(info);
                // console.log('当呈现一组新的日期时触发。')
            },

            // 两个事件都是全天活动时才允许重叠
            eventOverlap(stillEvent, movingEvent) {
                return stillEvent.allDay && movingEvent.allDay;
            },
            // 点击日期格子事件
            dayClick(date) {
                if (this.clickDate != null) {
                    this.clickDate(date);
                }
            },
            // 点击日历格子内的事件，点击事件
            eventClick(date) {
                // console.log(date);
                if (this.eventClicked != null) {
                    this.eventClicked(date)
                }

                // console.log(date.event.start,date.event.end);
                // let start = dateUtil.formatDate(new Date(date.event.start));
                // let end = dateUtil.formatDate(new Date(date.event.end));
                // console.log(start);
            },
            // 选择日期格子添加事件
            select(date) {
                // console.log(date);
                if (this.selectDate != null) {
                    this.selectDate(date);
                }

                // var title = prompt('新增事件:');  //这个是window的弹窗事件，可以根据需要改成项目中使用框架的弹窗，这里使用easyui的vue版框架
                //  this.$messager.prompt({
                //   title: "新增事件:",
                //   icon: "info",
                //   msg: "请输入事件名称",
                //   result: r => {
                //     if (r) {
                //       // 日历的添加事件
                //       this.calendarApi.addEvent({
                //         title: r,
                //         start: date.start,
                //         end: date.end,
                //         allDay: date.allDay
                //       });
                //       this.calendarApi.unselect()   //注销选择事件
                //     }
                //   }
                // });
            },

            // 日期格子内划入事件时触发，鼠标滑过，鼠标划入
            eventMouseEnter(info) {
                //可从info中解构我们需要的东西
                // console.log('划入事件时触发。',info)
            },

            // 获取插件中的方法，比如回到今天的today()方法,下面的为自定义的
            backToday() {
                // console.log("回到今天！");
                let calendarApi = this.$refs.fullCalendar.getApi(); //通过getApi()方法获取
                calendarApi.today(); //调用回到今天的today()方法
            },


        }
    };
</script>
<style>
    /* “~”指向 node_modules */
    /* @import '~@fullcalendar/core/main.css';
    @import '~@fullcalendar/daygrid/main.css';
    @import '~@fullcalendar/timegrid/main.css'; */

    .container-calender {
        position: absolute;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
    }

    .container-calender-son {
        position: absolute;
        top: 10px;
        left: 10px;
        right: 10px;
        bottom: 10px;
        overflow: hidden; /* don't do scrollbars */
        font-size: 14px;
    }

    .fc td,
    .fc-theme-standard td {
        position: relative;
    }

    .fc .fc-bg-event {
        opacity: 1;
    }

    .fc .fc-daygrid-body-unbalanced .fc-daygrid-day-events {
        cursor: default;
    }
</style>
